﻿using Dyd.BaseService.ServiceCenter.Domain;
using Dyd.BaseService.ServiceCenter.Domain.Bll;
using Dyd.BaseService.ServiceCenter.Domain.Model;
using Dyd.BaseService.ServiceCenter.Web.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using XXF.BaseService.ServiceCenter.Service.Protocol;
using XXF.Db;
using System.Linq;

namespace Dyd.BaseService.ServiceCenter.Web.Controllers
{
    [Authorize]
    public class ServiceController : Controller
    {

        #region List
        /// <summary>
        /// 
        /// </summary>
        /// <param name="search">查询实体</param>
        /// <param name="pno">页码</param>
        /// <param name="pagesize">页大小</param>
        /// <returns></returns>
        public ActionResult ServiceIndex(tb_service_search search)
        {
            int total = 0;
            IList<tb_service> list = new List<tb_service>();
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ServiceCenterConnectString))
            {
                conn.Open();
                list = tb_service_bll.Instance.GetPageList(conn, search, out total);
                var pagelist = new SPagedList<tb_service>(list, search.Pno, search.PageSize, total);

                if (Request.IsAjaxRequest())
                {
                    return PartialView("_ServiceIndex", pagelist);
                }
                else
                {
                    return View(pagelist);
                }
            }
        }
        #endregion

        #region Create
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="id">Id</param>
        /// <returns></returns>
        public ActionResult ServiceCreate()
        {
            return View();
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model">实体</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ServiceCreate(ServiceViewModel model)
        {
            //if (!ModelState.IsValid)
            //{
            //    return View();
            //}
            try
            {
                var dt = DateTime.Now;
                model.tb_service.createtime = dt;
                model.tb_service.protocolversionupdatetime = dt;
                model.tb_service.serviceupdatetime = dt;
                using (DbConn conn = DbConfig.CreateConn(DataConfig.ServiceCenterConnectString))
                {
                    conn.Open();
                    if (tb_service_bll.Instance.IsExists(conn, model.tb_service))
                    {
                        return Json(new { Flag = false, Message = "服务重复！" });
                    }

                    tb_service_bll.Instance.Add(conn, model.tb_service);
                    //tb_service_bll.Instance.Add(conn, model.tb_service, model.tb_protocolversion);
                    return Json(new { Flag = true, Message = "添加成功！" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Flag = false, Message = ex.Message });
            }
        }

        #endregion

        #region Edit

        /// <summary>
        /// 修改服务
        /// </summary>
        /// <param name="id">Id</param>
        /// <returns></returns>
        public ActionResult ServiceEdit(int id)
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ServiceCenterConnectString))
            {
                conn.Open();
                var serviceModel = tb_service_bll.Instance.Get(conn, id);
                var protocolVersionModel = tb_protocolversion_bll.Instance.Get(conn, serviceModel.id, serviceModel.protocolversion);
                ServiceViewModel view = new ServiceViewModel
                {
                    tb_service = serviceModel ?? new tb_service(),
                    tb_protocolversion = protocolVersionModel ?? new tb_protocolversion()
                };
                return View(view);
            }
        }

        /// <summary>
        /// 修改服务
        /// </summary>
        /// <param name="model">实体</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult ServiceEdit(ServiceViewModel model)
        {
            try
            {
                using (DbConn conn = DbConfig.CreateConn(DataConfig.ServiceCenterConnectString))
                {
                    conn.Open();
                    if (tb_service_bll.Instance.IsExists(conn, model.tb_service))
                    {
                        return Json(new { Flag = false, Message = "服务名重复！" });
                    }
                    model.tb_service.protocolversionupdatetime = conn.GetServerDate();
                    model.tb_service.serviceupdatetime = conn.GetServerDate();
                    tb_service_bll.Instance.Update(conn, model.tb_service);
                    return Json(new { Flag = true, Message = "修改成功！" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Flag = false, Message = ex.Message });

            }
        }

        #endregion

        #region ServiceDetails

        /// <summary>
        /// 查看服务
        /// </summary>
        /// <param name="id">Id</param>
        /// <returns></returns>
        public ActionResult ServiceDetails(int id)
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ServiceCenterConnectString))
            {
                conn.Open();
                var serviceModel = tb_service_bll.Instance.Get(conn, id);
                var protocolVersionModel = tb_protocolversion_bll.Instance.Get(conn, serviceModel.id, serviceModel.protocolversion);
                ServiceViewModel view = new ServiceViewModel
                {
                    tb_service = serviceModel ?? new tb_service(),
                    tb_protocolversion = protocolVersionModel ?? new tb_protocolversion()
                };
                return View(view);
            }
        }

        #endregion

        #region Delete
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ServiceDelete(int id)
        {
            try
            {
                using (DbConn conn = DbConfig.CreateConn(DataConfig.ServiceCenterConnectString))
                {
                    conn.Open();
                    tb_service_bll.Instance.Delete(conn, id);
                    return Json(new { Flag = true, Message = "删除成功！" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Flag = false, Message = ex.Message });

            }
        }
        #endregion

        #region APIDoc
        [OutputCache(Duration = 60, VaryByParam = "*")]

        public ActionResult ApiDoc(string key = "", int serviceid = 0)
        {
            try
            {
                key = key.Trim();
                ViewBag.key = key;
                ViewBag.id = serviceid;
                ApiDoc apiDoc = new ApiDoc();
                using (DbConn conn = DbConfig.CreateConn(DataConfig.ServiceCenterConnectString))
                {
                    conn.Open();
                    int totalCount;
                    var serviceSearch = new tb_service_search();
                    if (!string.IsNullOrWhiteSpace(key))
                    {
                        serviceSearch.key = key;
                    }
                    serviceSearch.id = serviceid;
                    serviceSearch.PageSize = int.MaxValue;

                    var menuList = tb_service_bll.Instance.GetPageList(conn, new tb_service_search(), out totalCount);
                    //CacheHelper.GetCache<IList<tb_service>>("tb_service_list", TimeSpan.FromMinutes(1), () =>
                    //     {
                    //         return tb_service_bll.Instance.GetPageList(conn, new tb_service_search(), out totalCount);
                    //     });


                    var serviceList = tb_service_bll.Instance.GetPageList(conn, serviceSearch, out totalCount);

                    if (!string.IsNullOrWhiteSpace(key))
                    {
                        menuList = Highlight(menuList, serviceList, key);
                    }
                    ViewBag.MenuList = menuList;

                    foreach (var service in serviceList)
                    {
                        var protocolversionSearch = new tb_protocolversion_search();
                        if (!string.IsNullOrWhiteSpace(key))
                        {
                            protocolversionSearch.key = key;
                        }
                        ////只显示当前版本
                        protocolversionSearch.version = service.protocolversion;
                        protocolversionSearch.PageSize = int.MaxValue;
                        protocolversionSearch.serviceid = service.id;

                        var versionList = tb_protocolversion_bll.Instance.GetPageList(conn, protocolversionSearch, out totalCount);
                        ServiceDoc serviceDoc = new ServiceDoc();
                        serviceDoc.ServiceName = service.servicename;
                        serviceDoc.ServiceId = service.id;
                        serviceDoc.ServiceNamespace = service.servicenamespace;
                        foreach (var version in versionList)
                        {
                            var v = JsonConvert.DeserializeObject<ServiceProtocal>(version.protocoljson);
                            serviceDoc.ServiceProtocalList.Add(v);
                        }
                        apiDoc.ServiceDocList.Add(serviceDoc);
                    }

                    if (!string.IsNullOrWhiteSpace(key))
                    {
                        apiDoc = Highlight(apiDoc, key);
                    }
                    return View(apiDoc);
                }
            }
            catch
            {
                return View();
            }
        }

        private ApiDoc Highlight(ApiDoc doc, string key)
        {
            var replaceStr = "<span style='color:red;'>" + key + "</span>";
            foreach (var item in doc.ServiceDocList)
            {
                item.ServiceName = item.ServiceName.Replace(key, replaceStr);
                item.ServiceNamespace = item.ServiceNamespace.Replace(key, replaceStr);
                foreach (var protocal in item.ServiceProtocalList)
                {
                    foreach (var method in protocal.MethodProtocols)
                    {
                        method.Name = method.Name.Replace(key, replaceStr);
                        foreach (var inputParam in method.InputParams)
                        {
                            inputParam.Name = inputParam.Name.Replace(key, replaceStr);
                            if (inputParam.IsCustomType)
                            {
                                inputParam.TypeName = inputParam.TypeName.Replace(key, replaceStr);
                            }
                        }
                    }
                    foreach (var entity in protocal.EntityProtocals)
                    {
                        entity.EntityDoc.Description = entity.EntityDoc.Description.Replace(key, replaceStr);
                        entity.EntityDoc.Text = entity.EntityDoc.Description.Replace(key, replaceStr);
                        entity.Name = entity.Name.Replace(key, replaceStr);
                        foreach (var property in entity.PropertyParams)
                        {
                            property.Name = property.Name.Replace(key, replaceStr);

                        }
                        foreach (var property in entity.PropertyDocs)
                        {
                            property.Description = property.Description.Replace(key, replaceStr);
                            property.Text = property.Text.Replace(key, replaceStr);
                        }

                    }
                }
            }
            return doc;
        }

        private IList<tb_service> Highlight(IList<tb_service> menuList, IList<tb_service> serviceList, string key)
        {
            var replaceStr = "<span style='color:red;'>" + key + "</span>";
            foreach (var item in menuList)
            {
                item.servicename = item.servicename.Replace(key, replaceStr);

                if (serviceList.Any(s => s.id == item.id))
                {
                    item.servicename = "<span style='background-color: #6CB3D5;'>" + item.servicename + "</span>";
                }
            }
            return menuList;
        }
        #endregion

    }
}